#!/usr/bin/python
# -*- coding: utf-8 -*-

# Author : amit shrestha

import urllib2
import urllib
import cookielib
import re

class FBI:
    """provides an easy interface for robot to access its facebook account

       note: functions and variables whose names begin with __ are private
    """
    
    def __init__(self, email, password):
        self.__cookie_jar = cookielib.LWPCookieJar()
        self.__browser = urllib2.build_opener(
            urllib2.HTTPCookieProcessor(self.__cookie_jar), 
            urllib2.HTTPRedirectHandler()
        )
        self.__browser.addheaders = [
            ('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
        ]
        urllib2.install_opener(self.__browser)
        self.__login(email, password)
    
    def __extract_own_id(self):
        #home page
        page = self.__browser.open('http://www.facebook.com/home.php?')
        contents = page.read()
        page.close()
        
        pattern = re.compile(r'Env=\{user:(\d+),')
        match = pattern.search(contents)
        if match: return match.group(1)
        else: return ''
         
    def __login(self, email, password):
        params = urllib.urlencode({
            'email': email, 
            'pass': password,
            'locale': 'en_US',
            'non_com_login': '',
            'charset_test':'€,´,€,´,水,Д,Є',
            'persistent':'0',
            'lsd': 'nZRRd'
        })

        #get required cookies first
        page = self.__browser.open('http://www.facebook.com')
        page.close()

        #login
        request = urllib2.Request('https://login.facebook.com/login.php?login_attempt=1')
        page = self.__browser.open(request,params)
        page.close()

        self.__id = self.__extract_own_id()
    
    def __cleanup(self,str):
        """returns str without non-sensical markups
        """
        str = str.replace(r'<br />','')
        str = str.replace(r'&#039;',"'")
        str = str.replace(r'&amp;',"and")
        return re.sub(r'<.*?>(.*?)</.*?>',r'\1',str)

    def get_friends(self, id=None):
         """returns friends of person with given id as (id,name) tuples

         If id is not provided, returns robot's friends
         """
         if id == None:
             id = self.__id

         url = "http://www.facebook.com/ajax/social_graph/dialog/popup.php?id=%s&__a=1&__d=1" % id
         page = self.__browser.open(url)
         contents = page.read()
         page.close()

         pattern = re.compile(r'id\\":(\d+),\\"title\\":\\"([a-z\sA-Z]+)\\",')
         matches = pattern.findall(contents)
         return matches

    def is_friend(self, name):
        """returns True if given name matches with any of robot's friends
        """

        friends = self.get_friends()
        for tid,tname in friends:
            if tname.lower() == name.lower():
                return True
        return False

    def get_profile(self, id):
        """returns profile of person with given id
        """
        url = "http://www.facebook.com/profile.php?id=%s&v=info" % id
        page = self.__browser.open(url)
        contents = page.read()
        page.close()

        #for some ids we are redirected
        pattern = re.compile('window\.location\.replace\("(.*?)"')
        match = pattern.search(contents)
        if match:
            url = match.group(1).replace('\\','')
            page = self.__browser.open(url)
            contents = page.read()
            page.close()

        keys = [
            'Sex', 
            'Current City', 
            'Birthday', 
            'Hometown', 
            'Political Views',
            'Religious Views',
            'Interests',
            'Favorite Music',
            'Favorite Movies'
        ]
        profile = {}

        for key in keys:
            pattern = re.compile('<dt>' + key + ':</dt><dd>(.*?)</dd>')
            match = pattern.search(contents)
            if match:
                profile[key] = self.__cleanup(match.group(1))

        return profile

if __name__ == "__main__":
    fbi = FBI('clarence.wubble@gmail.com','wubbleworld')
    friends = fbi.get_friends()

    print "**My Friends:"
    for id,name in friends:
        print "##%s, %s" % (name,id)
        print fbi.get_profile(id)

    print "** Friends of my first friend:"
    ffriends = fbi.get_friends(friends[0][0])
    for i in range(len(ffriends)):
        print ffriends[i][1]

    print fbi.is_friend("Amit Shrestha")
